package com.neo.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neo.model.User;
import com.neo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;


@Slf4j
@Controller
@RequestMapping("api/v1/user")
public class UserController {

    @Resource
    private UserService userService;


    /**
     * 删除用户接口
     *
     * @param id t_user表的主键id
     * @return
     */
    @RequestMapping("/delete/{id}")
    public String deleteUser(@PathVariable("id") String id) {
        userService.removeById(id);
        return "redirect:/api/v1/user/list";
    }

    /**
     * 根据id修改用户信息
     *
     * @param model
     * @param id
     * @return
     */
    @GetMapping("/updatePage/{id}")
    public String updatePage(Model model, @PathVariable String id) {
        User users = userService.getById(id);
        model.addAttribute("users", users);
        //表示跳转到modifie,html界面
        return "modifie";
    }

    /**
     * 编辑用户信息
     *
     * @param user    用户实体
     * @param request
     * @return
     */
    @PostMapping("/update")
    public String updateUser(User user, HttpServletRequest request) {
        log.info("update user,params:{}", user);
        userService.updateById(user);
        return "redirect:/api/v1/user/list";
    }

    /**
     * 跳转到新增页面
     *
     * @return
     */
    @GetMapping("/insert")
    public String insertOne() {
        return "add.html";
    }

    /**
     * 保存用户信息
     *
     * @param user 用户实体
     * @return
     */
    @PostMapping("/add")
    public String saveUser(User user) {
        log.info("save user,params:{}", user);
        String userId = UUID.randomUUID().toString().replaceAll("-", "");
        user.setUserId(userId);
        userService.save(user);
        //表示重置index.html界面并且跳转到index.html界面
        return "redirect:/api/v1/user/list";
    }

    /**
     * @param model model视图对象
     * @param pn    第几页
     * @return
     */
    @GetMapping("/list")
    public String getList(Model model, @RequestParam(value = "pn", defaultValue = "1") Integer pn) {
        //分页查询数据，每页显示5条，
        Page<User> userPage = new Page<>(pn, 10);
        //分页查询的结果
        Page<User> page = userService.page(userPage, null);
        model.addAttribute("page", page);
        List<User> userList = userService.getUserByUserAge("10");
        model.addAttribute("userList", userList);
        return "login.html";
    }

}
